﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Wicresoft.UnifyShow.Business;
using Wicresoft.UnifyShow2.Portal.Models;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class AdminBSController : BaseController
    {

        private IUser_X user;
        private IDevice device;
        private IBusinessSystem businessSystem;
        private ISiteBranch siteBranch;
        private IBusinessCategory businessCategory;
        private ISelfBS selfbs;

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user).Dispose();
            ((IDisposable)device).Dispose();
            ((IDisposable)businessSystem).Dispose();
            ((IDisposable)siteBranch).Dispose();
            ((IDisposable)businessCategory).Dispose();
            ((IDisposable)selfbs).Dispose();
        }

        [InjectionConstructor]
        public AdminBSController(IUser_X user, IDevice device, IBusinessSystem businessSystem,
            ISiteBranch siteBranch, IBusinessCategory businessCategory,ISelfBS selfbs)
        {
            this.user = user;
            this.device = device;
            this.businessSystem = businessSystem;
            this.siteBranch = siteBranch;
            this.businessCategory = businessCategory;
            this.selfbs = selfbs;
        }

        //
        // GET: /AdminDeviceAndBS/

        public ActionResult Add()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);

            BSAddModel dsAdd = new BSAddModel();
            //name 最好用拼音或者英文。
            ViewData["Categories"] = businessCategory.GetAllSiteCategory().
                Select(o => new SelectListItem()
                {
                    Text = o.CategoryAlias,
                    Value = o.CategoryName,
                    Selected = false
                });
            //根据当前用户所在公司名称返回SiteBranchModel                                   
            List<US_SiteAccessModel> listUS = new List<US_SiteAccessModel>();
            List<SiteBranchModel> listSites = new List<SiteBranchModel>();
            if (USER_X.Company == "福建省烟草专卖局")
            {
                listSites = siteBranch.GetSiteALLBranch();
            }
            else
            {
                listSites.Add(siteBranch.GetSiteBranchByName(USER_X.Company));
            }
            foreach (var item in listSites)
            {
                if (!string.IsNullOrEmpty(item.Alias))
                {
                    US_SiteAccessModel usmodel = new US_SiteAccessModel();
                    usmodel.ID = item.ID;
                    usmodel.Alias = item.Alias;
                    usmodel.IsAccess = false;
                    listUS.Add(usmodel);
                }
            }
            dsAdd.US_SiteAccessList = listUS;
            return View(dsAdd);
        }

        [HttpPost]
        public ActionResult Add(BSAddModel model)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            var listExsit = businessSystem.GetExistTheBSSites(model.SystemName);
            var listShare=listExsit.Where(d=>model.US_SiteAccessList.Where(o=>o.IsAccess==true).Select(o=>o.ID).Contains(d.ID)).ToList();
            if (listShare.Count > 0)
            {
                string sites = string.Empty;
                foreach (var item in listExsit)
                {
                    sites += item.Alias+"、";
                }
                ViewBag.error = sites;
            }
            else
            {
                List<BusinessSystemModel> list = new List<BusinessSystemModel>(); ;
                BusinessSystemModel m;
                var select = model.US_SiteAccessList.Where(o => o.IsAccess == true);
                List<Dictionary<uint, string>> syncs = new List<Dictionary<uint, string>>();
                Dictionary<uint, string> sync = null;
                foreach (var item in select)
                {
                    m = new BusinessSystemModel();
                    m.Name = model.SystemName;
                    m.Alias = model.SystemName;
                    m.Category = model.SystemCategroy;
                    m.VendorInfo = model.VendorInfo;
                    m.OpInfo = model.OperateInfo;
                    m.FncInfo = model.AssetInfo;
                    m.SiteID = item.ID;
                    list.Add(m);

                    sync = new Dictionary<uint, string>();
                    sync[536890913] = siteBranch.GetSiteBranchByID(int.Parse(m.SiteID.ToString())).Name;
                    sync[536870915] = m.Category;
                    sync[536870925] = m.Name;
                    syncs.Add(sync);

                    ////Add Selfservice
                    //SelfBSModel sm = new SelfBSModel()
                    //{
                    //    Name = model.SystemName,
                    //    Company = siteBranch.GetSiteBranchByID(int.Parse(m.SiteID.ToString())).Name,
                    //    Category = model.SystemCategroy
                    //};
                    //selfbs.Add(sm);
                }
                //Add unifyshow
                businessSystem.AddList(list);

                //Add ITSM
                ARHelper.SyncAddListBusinessSystemToAR(syncs);
                SyncHelper.SyncAddListBusinessSystemToSelf(syncs);
                ViewBag.error = string.Empty;
            }
            //name 最好用拼音或者英文。
            ViewData["Categories"] = businessCategory.GetAllSiteCategory().
                Select(o => new SelectListItem()
                {
                    Text = o.CategoryAlias,
                    Value = o.CategoryName,
                    Selected = false
                });
            ViewBag.Post = true;
            return View(model);
        }

        public ActionResult Edit(int bsID)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            BusinessSystemModel model = businessSystem.GetBusinessSystemByID(bsID);
            List<SelectListItem> listItemsCategory = new List<SelectListItem>();
            SelectListItem itemTemp;
            foreach (var item in businessCategory.GetAllSiteCategory())
            {
                itemTemp = new SelectListItem()
                {
                    Text = item.CategoryAlias,
                    Value = item.CategoryName,
                    Selected = false
                };
                if (model.Category == item.CategoryName) itemTemp.Selected = true;
                listItemsCategory.Add(itemTemp);
            }
            ViewData["Categories"] = listItemsCategory;
            ViewData["Devices"] = device.GetServerBySiteIDBSID(model.SiteID, model.ID);
            ViewData["SiteName"] = siteBranch.GetSiteBranchByID(int.Parse(model.SiteID + "")).Name;
            return PartialView(model);
        }

        [HttpPost]
        public void Edit(BusinessSystemModel model)
        {
            //update ITSM
            BusinessSystemModel dbmodel = businessSystem.GetBusinessSystemByID((int)model.ID);
            List<Dictionary<uint, string>> syncs = new List<Dictionary<uint, string>>();
            Dictionary<uint, string> syncdelete = new Dictionary<uint, string>();
            syncdelete[536890913] = siteBranch.GetSiteBranchByID(int.Parse(dbmodel.SiteID.ToString())).Name;
            syncdelete[536870915] = dbmodel.Category;
            syncdelete[536870925] = dbmodel.Name;

            ARHelper.SyncDeleteBusinessSystemToAR(syncdelete);
            SyncHelper.SyncDeleteBusinessSystemToSelf(syncdelete);

            Dictionary<uint, string> sync = new Dictionary<uint, string>();
            sync[536890913] = siteBranch.GetSiteBranchByID(int.Parse(model.SiteID.ToString())).Name;
            sync[536870915] = model.Category;
            sync[536870925] = model.Name;

            syncs.Add(sync);

            ARHelper.SyncAddListBusinessSystemToAR(syncs);
            SyncHelper.SyncAddListBusinessSystemToSelf(syncs);

            //update unifyshow
            businessSystem.Update(model);

            ////update selfService
            //SelfBSModel sm = new SelfBSModel()
            //{
            //    Name = model.Name,
            //    Company = siteBranch.GetSiteBranchByID(int.Parse(model.SiteID.ToString())).Name,
            //    Category = model.Category
            //};
            //selfbs.Update(sm);

        }

        [HttpPost]
        public void Delete(int id)
        {
            BusinessSystemModel bs = businessSystem.GetBusinessSystemByID(id);
            //delete relationship with businessSystem and device
            device.InitBsIdByBsId(id);
            //delete unifyshow
            businessSystem.Delete(id);
            ////delete selfService
            //string company = siteBranch.GetSiteBranchByID(int.Parse(bs.SiteID.ToString())).Name;
            //selfbs.Delete(company, bs.Name);

            //delete ITSM
            Dictionary<uint, string> sync = new Dictionary<uint, string>();
            sync[536890913] = siteBranch.GetSiteBranchByID(int.Parse(bs.SiteID.ToString())).Name;
            sync[536870915] = bs.Category;
            sync[536870925] = bs.Name;

            ARHelper.SyncDeleteBusinessSystemToAR(sync);
            SyncHelper.SyncDeleteBusinessSystemToSelf(sync);
        }

        [HttpPost]
        public void Publish(int id)
        {
            //do something about the publish
        }

    }
}
